/**
 * @Copyright ®2015 Sinosoft Co. Ltd. All rights reserved.
 * 项目名称 : 网站服务平台
 * 创建日期 : 2016-11-14
 * 修改历史 :
 * 1. [2016-11-14]创建文件 by chenxin
 */
package com.sinosoft.sinopay.paytrade.biz.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sinosoft.sinocloud.common.biz.service.BizNumGenerateCoreService;
import com.sinosoft.sinocloud.platform.base.SinoBaseException;
import com.sinosoft.sinocloud.platform.base.SinoBaseService;
import com.sinosoft.sinocloud.platform.common.config.SystemConstants;
import com.sinosoft.sinocloud.platform.common.context.SpringContext;
import com.sinosoft.sinocloud.platform.common.exception.biz.BizDataErrException;
import com.sinosoft.sinocloud.platform.common.exception.biz.SinoBizException;
import com.sinosoft.sinocloud.platform.common.util.DateUtil;
import com.sinosoft.sinocloud.platform.common.util.StringUtil;
import com.sinosoft.sinopay.api.common.config.ENUM_PAY_BIZNO_TYPE;
import com.sinosoft.sinopay.api.common.config.ENUM_PAY_TYPE;
import com.sinosoft.sinopay.api.common.dto.pay.PayAccountInfoDTO;
import com.sinosoft.sinopay.api.common.dto.pay.PayInfoReturnDTO;
import com.sinosoft.sinopay.api.common.dto.pay.PaymentInfoDetailDTO;
import com.sinosoft.sinopay.api.pay.dto.InterPayRequestDTO;
import com.sinosoft.sinopay.api.pay.service.InterPayApiService;
import com.sinosoft.sinopay.payrules.dto.MerchantNotifyDTO;
import com.sinosoft.sinopay.payrules.dto.PayChannelCheckDTO;
import com.sinosoft.sinopay.payrules.dto.PayRouteCheckDTO;
import com.sinosoft.sinopay.payrules.facade.PayRuleFacade;
import com.sinosoft.sinopay.paytrade.biz.integration.mapper.PayOrderMapper;
import com.sinosoft.sinopay.paytrade.biz.integration.mapper.PayTradeMapper;
import com.sinosoft.sinopay.paytrade.biz.service.PaymentTradeCoreService;
import com.sinosoft.sinopay.paytrade.config.ENUM_ORDER_STATUS;
import com.sinosoft.sinopay.paytrade.config.ENUM_PAY_STATUS;
import com.sinosoft.sinopay.paytrade.dto.PayTradeNotifyRecordDTO;
import com.sinosoft.sinopay.paytrade.dto.PaymentConfirmDTO;
import com.sinosoft.sinopay.paytrade.dto.PaymentRequestDTO;
import com.sinosoft.sinopay.paytrade.dto.PaymentTradeBatchDTO;
import com.sinosoft.sinopay.paytrade.dto.PaymentTradeReqDTO;
import com.sinosoft.sinopay.paytrade.dto.UserAuthConfInfo;
import com.sinosoft.sinopay.paytrade.facade.PaymentTradeQueryFacadeService;
import com.sinosoft.sinopay.paytrade.generated.mapper.PayTradeBatchMapper;
import com.sinosoft.sinopay.paytrade.generated.mapper.PayTradeMainMapper;
import com.sinosoft.sinopay.paytrade.generated.mapper.PayTradeNotifyRecordLogMapper;
import com.sinosoft.sinopay.paytrade.generated.mapper.PayTradeNotifyRecordMapper;
import com.sinosoft.sinopay.paytrade.generated.mapper.PayTradeOfferLogMapper;
import com.sinosoft.sinopay.paytrade.generated.mapper.PayTradeOrderMapper;
import com.sinosoft.sinopay.paytrade.generated.mapper.PayTradePaymentBatchMapper;
import com.sinosoft.sinopay.paytrade.generated.mapper.RelaTradePaymentMapper;
import com.sinosoft.sinopay.paytrade.generated.model.PayTradeBatch;
import com.sinosoft.sinopay.paytrade.generated.model.PayTradeBatchExample;
import com.sinosoft.sinopay.paytrade.generated.model.PayTradeMain;
import com.sinosoft.sinopay.paytrade.generated.model.PayTradeMainExample;
import com.sinosoft.sinopay.paytrade.generated.model.PayTradeNotifyRecord;
import com.sinosoft.sinopay.paytrade.generated.model.PayTradeNotifyRecordExample;
import com.sinosoft.sinopay.paytrade.generated.model.PayTradeNotifyRecordLog;
import com.sinosoft.sinopay.paytrade.generated.model.PayTradeOfferLog;
import com.sinosoft.sinopay.paytrade.generated.model.PayTradeOfferLogExample;
import com.sinosoft.sinopay.paytrade.generated.model.PayTradeOrder;
import com.sinosoft.sinopay.paytrade.generated.model.PayTradePaymentBatch;
import com.sinosoft.sinopay.paytrade.generated.model.PayTradePaymentBatchExample;
import com.sinosoft.sinopay.paytrade.generated.model.RelaTradePayment;
import com.sinosoft.sinopay.paytrade.generated.model.RelaTradePaymentExample;
import com.sinosoft.sinopay.paytrade.util.RandomStringUtil;

/**
 * 【支付交易服务接口实现类】
 * @author chenxin
 * @date 2016-11-14 下午4:54 
 * @version V1.0
 */
@Service
public class PaymentTradeCoreServiceImpl extends SinoBaseService implements PaymentTradeCoreService {
    /** 交易备注长度限制 */
    private Integer REMARK_LENTH_MAX = 15;
    @Autowired
    private BizNumGenerateCoreService bizNumGeneratorService;

    @Autowired
    private PayTradeOrderMapper payTradeOrderMapper;

    @Autowired
    private PayTradeMainMapper payTradeMainMapper;
    
    @Autowired
    private PayOrderMapper payOrderMapper;
    
    @Autowired
    private PayTradeBatchMapper payTradeBatchMapper;
	
	@Autowired
    private PayTradePaymentBatchMapper payTradePaymentBatchMapper;
    
	@Autowired
    private PayTradeOfferLogMapper payTradeOfferLogMapper;
	
	@Autowired
    private RelaTradePaymentMapper relaTradePaymentMapper;
    
	@Autowired
    private PayTradeNotifyRecordMapper payTradeNotifyRecordMapper;
	
	@Autowired
    private PayTradeNotifyRecordLogMapper payTradeNotifyRecordLogMapper;
    
    @Autowired
	private PaymentTradeQueryFacadeService paymentTradeQryFacadeService;
    
    @Autowired
	private PayRuleFacade payRuleFacade;
    
    @Autowired
    private PayTradeMapper payTradeMapper;
    
	@Override
    public UserAuthConfInfo comfirmNewPaymentRequest(String PayNo) {
    	//1.获取支付相关 订单信息 
    	PaymentInfoDetailDTO tPayInfo = paymentTradeQryFacadeService.queryPaymentOrderByPayNo(PayNo);
    	BigDecimal tPayAmount = tPayInfo.getPayAmount().setScale(2, BigDecimal.ROUND_HALF_DOWN);
    	//2.调用支付路由
    	PayRouteCheckDTO payRouteCheckDTO = new PayRouteCheckDTO();
		payRouteCheckDTO.setPayAmount(tPayInfo.getPayAmount());
		payRouteCheckDTO.setPayType(tPayInfo.getPayType());
		logger.info("----请求支付路由----");
		PayRouteCheckDTO returnPayRouteCheckDTO = payRuleFacade.payRoute(payRouteCheckDTO);
    	//3.支付渠道 规则校验
		logger.info("----支付规则校验----");
		PayChannelCheckDTO payChannelCheckDTO = new PayChannelCheckDTO();
		payChannelCheckDTO.setPayAmount(returnPayRouteCheckDTO.getPayAmount());
		payChannelCheckDTO.setThirdpayCode(returnPayRouteCheckDTO.getThirdpayCode());
		payRuleFacade.checkPayChannel(payChannelCheckDTO);
		//4.调用接口支付API服务
		InterPayRequestDTO interPayRequestInfo = new InterPayRequestDTO();//查询订单信息
		interPayRequestInfo.setPayNo(PayNo);
		interPayRequestInfo.setAmount(tPayAmount);
		interPayRequestInfo.setAccountNo(tPayInfo.getAccountNo());
		interPayRequestInfo.setAccountName(tPayInfo.getAccountName());
		//银行编码 需要进行转码 操作；
		if (!"".equals(tPayInfo.getBankCode())&&null!=tPayInfo.getBankCode()) {
		    logger.info("----银行转码操作----");
		    String bankCodeTarget  = paymentTradeQryFacadeService.queryStandBankCodeByBankCode(tPayInfo.getBankCode());
		    interPayRequestInfo.setBankCode(bankCodeTarget);
	        Date date=new Date();   
	        SimpleDateFormat df=new SimpleDateFormat("yyyyMMddhhmmss");
	        logger.info("----请求支付时间标准化----");
	        String dateNow=df.format(date);
	        interPayRequestInfo.setSubmitTime(dateNow);   //请求时间 格式及类型 转换               
            logger.info("----获取具体的调用实现bean过程----");
	        InterPayApiService interPayApiService = (InterPayApiService)SpringContext.getBean(returnPayRouteCheckDTO.getThirdpayImplName());
	        PayInfoReturnDTO payInfoReturnDTO = new PayInfoReturnDTO();
	        try {
	            logger.info("----调用API 获取返回结果信息----");
	            payInfoReturnDTO = interPayApiService.payRequest(interPayRequestInfo);
	        } catch (SinoBaseException ee) {
	            ee.printStackTrace();
	            throw new SinoBizException(ee.getMessage());
	        } catch (Exception e) {
	            e.printStackTrace();
	            throw new SinoBizException("系统异常"+e.getMessage());
	        } 
	        //获取商户回调URL  前段回调URL "S1_F", "网关支付前台"返 出去 ，"S1_B", "网关支付后台"存表 根据merchantID 查询merchantCode信息
	        List<MerchantNotifyDTO> tMerchantNotifyList = payRuleFacade.queryMerchantNotifyUrl(tPayInfo.getMerchantCode());
	        //跟据 网关支付 返回结果信息 执行  更新 订单状态 记录主表  记录回调表 、日志表   。 超过三次失败 不允许查询回调URL信息
	        if (payInfoReturnDTO.getReturnCode().equals("0000")||"SUCCESS".equals(payInfoReturnDTO.getReturnCode())) { // 根据订单号 更新 订单状态
	            PaymentConfirmDTO tPaymentConfirmDTO = new PaymentConfirmDTO();
	            tPaymentConfirmDTO.setPayNo(PayNo);   
	            tPaymentConfirmDTO.setPayStatus(ENUM_PAY_STATUS.PAY_PAYED.code()); //已支付：03
	            int modifyFlag = modifyTradeOrderStatus(tPaymentConfirmDTO);   //根据订单号修改订单状态  
	            if (modifyFlag>0) {
	                logger.info("----修改订单支付状态成功----");
	            }
	            PaymentTradeReqDTO tPaymentTradeReqDTO = new PaymentTradeReqDTO();   
	            tPaymentTradeReqDTO.setPayNo(PayNo);
	            tPaymentTradeReqDTO.setOrderId(tPayInfo.getSid());
	            tPaymentTradeReqDTO.setMerchantCode(tPayInfo.getMerchantCode());
	            tPaymentTradeReqDTO.setBizNo(tPayInfo.getBizNo());
	            tPaymentTradeReqDTO.setSerialNo(tPayInfo.getSerialNo());
	            tPaymentTradeReqDTO.setBizType(tPayInfo.getBizType());
	            tPaymentTradeReqDTO.setPayAmount(tPayInfo.getPayAmount());
	            tPaymentTradeReqDTO.setPayAccountName(tPayInfo.getAccountName());
	            tPaymentTradeReqDTO.setPayIdType(tPayInfo.getIdType());
	            tPaymentTradeReqDTO.setPayIdNo(tPayInfo.getIdNo());
	            tPaymentTradeReqDTO.setPayBankCode(tPayInfo.getBankCode());
	            tPaymentTradeReqDTO.setPayBankName(tPayInfo.getBankName());
	            tPaymentTradeReqDTO.setPayAccountNo(tPayInfo.getAccountNo());
	            tPaymentTradeReqDTO.setPayAccountMobile(tPayInfo.getMobile());
	            tPaymentTradeReqDTO.setCreateDate(tPayInfo.getCreateDate());
	            tPaymentTradeReqDTO.setTradeDesc(tPayInfo.getTradeDesc());
	            tPaymentTradeReqDTO.setRemark(tPayInfo.getRemark());
	            tPaymentTradeReqDTO.setThirdpayCode(tPayInfo.getThirdpayCode());
	            tPaymentTradeReqDTO.setPayType(tPayInfo.getPayType());
	            tPaymentTradeReqDTO.setPayStatus(ENUM_PAY_STATUS.PAY_PAYED.code());
	            tPaymentTradeReqDTO.setSid(tPayInfo.getSid());
	            tPaymentTradeReqDTO.setReqBatchNo(tPayInfo.getReqBatchNo());
	            tPaymentTradeReqDTO.setPayCertType(tPayInfo.getCertType());
	            tPaymentTradeReqDTO.setPayOpenBank(tPayInfo.getBankCode());
	            tPaymentTradeReqDTO.setPayOpenBankArea(tPayInfo.getOpenBankArea());
	            tPaymentTradeReqDTO.setCurrency(tPayInfo.getCurrency());
	            tPaymentTradeReqDTO.setCheckDate(DateUtil.getCurrentDate());
	            tPaymentTradeReqDTO.setCreatorId(SystemConstants.SYS_OPERATOR);
	            tPaymentTradeReqDTO.setPayDate(DateUtil.getCurrentDate());
	            tPaymentTradeReqDTO.setTradeTimes(1);
	            tPaymentTradeReqDTO.setPayAmount(tPayAmount);
	            tPaymentTradeReqDTO.setReturnCode(payInfoReturnDTO.getReturnCode());
	            tPaymentTradeReqDTO.setReturnMsg(payInfoReturnDTO.getReturnMsg());
	            Integer modifyPaymentFlag = addPaymentInfo(tPaymentTradeReqDTO); // 插入支付主表支付信息
	            if (modifyPaymentFlag>0) {
	                //System.out.println("新增支付主表 订单记录成功");
	                logger.info("----新增支付主交易结果信息 成功----");
	            }
	            // 支付返回之后 记录回调表  第一次为新增 记录相关信息  ，传如后台URL 更新回调表
	            for (int i = 0; i < tMerchantNotifyList.size(); i++) {
	                if ("S1_B".equals(tMerchantNotifyList.get(i).getNotifyType())) {  //后台URL 更新信息
	                    PayTradeNotifyRecordDTO tPayTradeNotifyRecordDTO = new PayTradeNotifyRecordDTO();
	                    tPayTradeNotifyRecordDTO.setMerchantCode(tPayInfo.getMerchantCode());
	                    tPayTradeNotifyRecordDTO.setPayNo(PayNo);
	                    tPayTradeNotifyRecordDTO.setNotifyUrl(tMerchantNotifyList.get(i).getNotifyUrl());
	                    tPayTradeNotifyRecordDTO.setNotifyType(tMerchantNotifyList.get(i).getNotifyType());
	                    tPayTradeNotifyRecordDTO.setNotifyTimes(1);   //成功的时候 默认会掉次数为1
	                    tPayTradeNotifyRecordDTO.setLimitNotifyTimes(5);
	                    /*tPayTradeNotifyRecordDTO.setNotifyResult(payInfoReturnDTO.getReturnCode());*/
	                    tPayTradeNotifyRecordDTO.setCreatorId(SystemConstants.SYS_OPERATOR);
	                    tPayTradeNotifyRecordDTO.setCreateDate(DateUtil.getCurrentDate());
	                    Integer addFlag = addPayTradeNotifyRecord(tPayTradeNotifyRecordDTO);  //返回流水号 
	                    if (addFlag>0) {
	                        //System.out.println("新增 回调记录信息 成功");
	                        logger.info("----新增 回调记录信息 成功----");
	                    }
	                }
	            }
	        }else {    //返回失败 标记处理过程
	            // 根据订单号 更新 订单状态
	            PaymentConfirmDTO tPaymentConfirmDTO = new PaymentConfirmDTO();
	            tPaymentConfirmDTO.setPayNo(PayNo);    
	            tPaymentConfirmDTO.setPayStatus(ENUM_PAY_STATUS.PAY_FAIL.code()); //支付失败：05
	            int modifyFlag = modifyTradeOrderStatus(tPaymentConfirmDTO);      //根据订单号修改订单状态
	            if (modifyFlag>0) {
	                //System.out.println("订单状态修改成功");
	                logger.info("----修改订单支付状态成功----");
	            }
	            PaymentTradeReqDTO tPaymentTradeReqDTO = new PaymentTradeReqDTO();  // 插入支付主表支付信息 
	            tPaymentTradeReqDTO.setPayNo(PayNo);
	            tPaymentTradeReqDTO.setOrderId(tPayInfo.getSid());
	            tPaymentTradeReqDTO.setMerchantCode(tPayInfo.getMerchantCode());
	            tPaymentTradeReqDTO.setBizNo(tPayInfo.getBizNo());
	            tPaymentTradeReqDTO.setSerialNo(tPayInfo.getSerialNo());
	            tPaymentTradeReqDTO.setBizType(tPayInfo.getBizType());
	            tPaymentTradeReqDTO.setPayAmount(tPayInfo.getPayAmount());
	            tPaymentTradeReqDTO.setPayAccountName(tPayInfo.getAccountName());
	            tPaymentTradeReqDTO.setPayIdType(tPayInfo.getIdType());
	            tPaymentTradeReqDTO.setPayIdNo(tPayInfo.getIdNo());
	            tPaymentTradeReqDTO.setPayBankCode(tPayInfo.getBankCode());
	            tPaymentTradeReqDTO.setPayBankName(tPayInfo.getBankName());
	            tPaymentTradeReqDTO.setPayAccountNo(tPayInfo.getAccountNo());
	            tPaymentTradeReqDTO.setPayAccountMobile(tPayInfo.getMobile());
	            tPaymentTradeReqDTO.setCreateDate(tPayInfo.getCreateDate());
	            tPaymentTradeReqDTO.setTradeDesc(tPayInfo.getTradeDesc());
	            tPaymentTradeReqDTO.setRemark(tPayInfo.getRemark());
	            tPaymentTradeReqDTO.setThirdpayCode(tPayInfo.getThirdpayCode());
	            tPaymentTradeReqDTO.setPayType(tPayInfo.getPayType());
	            tPaymentTradeReqDTO.setPayStatus(ENUM_PAY_STATUS.PAY_FAIL.code());
	            tPaymentTradeReqDTO.setSid(tPayInfo.getSid());
	            tPaymentTradeReqDTO.setReqBatchNo(tPayInfo.getReqBatchNo());
	            tPaymentTradeReqDTO.setPayCertType(tPayInfo.getCertType());
	            tPaymentTradeReqDTO.setPayOpenBank(tPayInfo.getBankCode());
	            tPaymentTradeReqDTO.setPayOpenBankArea(tPayInfo.getOpenBankArea());
	            tPaymentTradeReqDTO.setCurrency(tPayInfo.getCurrency());
	            tPaymentTradeReqDTO.setCheckDate(DateUtil.getCurrentDate());
	            tPaymentTradeReqDTO.setCreatorId(SystemConstants.SYS_OPERATOR);
	            tPaymentTradeReqDTO.setPayDate(DateUtil.getCurrentDate());
	            tPaymentTradeReqDTO.setTradeTimes(1);
	            tPaymentTradeReqDTO.setPayAmount(tPayAmount);
	            tPaymentTradeReqDTO.setReturnCode(payInfoReturnDTO.getReturnCode());
                tPaymentTradeReqDTO.setReturnMsg(payInfoReturnDTO.getReturnMsg());
	            Integer modifyPaymentFlag = addPaymentInfo(tPaymentTradeReqDTO);
	            if (modifyPaymentFlag>0) {
	                //System.out.println("新增订单记录成功");
	                logger.info("----新增支付主交易结果信息 成功----");
	            }
	            for (int i = 0; i < tMerchantNotifyList.size(); i++) { // 支付返回之后 记录回调表  第一次为新增 记录相关信息 传如后台URL 更新回调表
	                if ("S1_B".equals(tMerchantNotifyList.get(i).getNotifyType())) {  //后台URL 更新信息
	                    PayTradeNotifyRecordDTO tPayTradeNotifyRecordDTO = new PayTradeNotifyRecordDTO();
	                    //根据订单号查询 之前有无回调记录 ，没有插入，有的话更新回调次数
	                    tPayTradeNotifyRecordDTO.setMerchantCode(tPayInfo.getMerchantCode());
	                    tPayTradeNotifyRecordDTO.setPayNo(PayNo);
	                    tPayTradeNotifyRecordDTO.setNotifyUrl(tMerchantNotifyList.get(i).getNotifyUrl());
	                    tPayTradeNotifyRecordDTO.setNotifyType(tMerchantNotifyList.get(i).getNotifyType());
	                    tPayTradeNotifyRecordDTO.setNotifyTimes(1);   //成功的时候 默认会掉次数为1
	                    tPayTradeNotifyRecordDTO.setLimitNotifyTimes(5);
	                    /*tPayTradeNotifyRecordDTO.setNotifyResult(payInfoReturnDTO.getReturnCode());*/
	                    tPayTradeNotifyRecordDTO.setCreatorId(SystemConstants.SYS_OPERATOR);
	                    tPayTradeNotifyRecordDTO.setCreateDate(DateUtil.getCurrentDate());
	                    Integer addFlag =  addPayTradeNotifyRecord(tPayTradeNotifyRecordDTO);  //返回流水号 
	                    if (addFlag>0) {
	                        //System.out.println("新增回调记录信息成功");
	                        logger.info("----新增 回调记录信息 成功----");
	                    }       
	                }
	            }   
	        }
	        UserAuthConfInfo tUserAuthConfInfo = new UserAuthConfInfo();  //前端回调URL"S1_F"返回信息
	        for (int i = 0; i < tMerchantNotifyList.size(); i++) {
	            if ("S1_F".equals(tMerchantNotifyList.get(i).getNotifyType())) {
	                tUserAuthConfInfo.setPayType(tMerchantNotifyList.get(i).getPayType());  //支付方式
	                tUserAuthConfInfo.setNotifyType(tMerchantNotifyList.get(i).getNotifyType());  //回调通知类型 
	                tUserAuthConfInfo.setNotifyUrl(tMerchantNotifyList.get(i).getNotifyUrl());  //回调通知URL
	                if (payInfoReturnDTO.getReturnCode().equals("0000")||"SUCCESS".equals(payInfoReturnDTO.getReturnCode())) {
	                    tUserAuthConfInfo.setReturnCode("SUCCESS");
	                }else {
	                    tUserAuthConfInfo.setReturnCode("FAIL");  
                    }
	                tUserAuthConfInfo.setReturnMsg(payInfoReturnDTO.getReturnMsg());
	                
	            }
	        }
	        return tUserAuthConfInfo;
        }else {
            UserAuthConfInfo tUserAuthConfInfo = new UserAuthConfInfo();  //前端回调URL"S1_F"返回信息
            tUserAuthConfInfo.setPayType("暂未获取到相关信息");  //支付方式
            tUserAuthConfInfo.setNotifyType("暂未获取到相关信息");  //回调通知类型 
            tUserAuthConfInfo.setNotifyUrl("银行编码 暂未调用交易服务");  //回调通知URL
            tUserAuthConfInfo.setReturnCode("FAIL");
            tUserAuthConfInfo.setReturnMsg("错误：请求参数 银行编码为空");
            return tUserAuthConfInfo;
        }
		
    }
	
    @Override
    public String addNewPayTrade(PaymentRequestDTO cPayReqInfo) {
        Date tCurrentDate = DateUtil.getCurrentDate();
        String tTradeDesc = cPayReqInfo.getRemark();
        if(tTradeDesc !=null && tTradeDesc.length()>REMARK_LENTH_MAX){
            throw new BizDataErrException("交易描述信息过长,超过" + REMARK_LENTH_MAX + "个字,描述信息为" + tTradeDesc);
        }
        PayTradeOrder payTradeOrder = new PayTradeOrder();
        PayAccountInfoDTO tPayAccount = cPayReqInfo.getPayAccount();
        payTradeOrder.setAccountName(tPayAccount.getAccountName());
        payTradeOrder.setAccountNo(cPayReqInfo.getPayAccount().getAccountNo());
        payTradeOrder.setBankCode(tPayAccount.getBankCode());
        payTradeOrder.setBankName(tPayAccount.getBankName());
        payTradeOrder.setBizNo(cPayReqInfo.getBizNo());
        payTradeOrder.setBizType(cPayReqInfo.getBizType());
        if ((Object)(cPayReqInfo.getCreateDate())==null) {  //交易时间为空 ，存放系统时间
           payTradeOrder.setCreateDate(tCurrentDate); //当前存放交易时间
        }else {
           payTradeOrder.setCreateDate(cPayReqInfo.getCreateDate());
        }
        payTradeOrder.setCreatorId(SystemConstants.SYS_OPERATOR);
        payTradeOrder.setCurrency("RMB");
        payTradeOrder.setIdNo(tPayAccount.getCardNo());
        payTradeOrder.setIdType(tPayAccount.getCardType());
        payTradeOrder.setMerchantCode(cPayReqInfo.getMerchantCode());
        payTradeOrder.setMobile(tPayAccount.getMobile());
        payTradeOrder.setModifierId(SystemConstants.SYS_OPERATOR);
        payTradeOrder.setModifyDate(tCurrentDate);
        payTradeOrder.setPayFlag("S");
        payTradeOrder.setPayType(ENUM_PAY_TYPE.GATEWAY.code());
        /** 生成支付号 */
        String tPayNo = bizNumGeneratorService.generateBizNum(ENUM_PAY_BIZNO_TYPE.PAYNO.code());
        payTradeOrder.setPayNo(tPayNo);
        payTradeOrder.setPayStatus(ENUM_ORDER_STATUS.TOPAY.code());
        payTradeOrder.setReqBatchNo("000000");
        payTradeOrder.setSerialNo(cPayReqInfo.getSerialNo());
        payTradeOrder.setTradeAmount(cPayReqInfo.getPayAmount());
        payTradeOrder.setTradeDesc(tTradeDesc);
        payTradeOrderMapper.insert(payTradeOrder);
        return tPayNo;
    }

    @Override
	public int modifyTradeOrderStatus(PaymentConfirmDTO cPayConfirmInfo) {
    	int updateStatus = payOrderMapper.updatePaymentOrderByPayNo(cPayConfirmInfo);
    	return updateStatus;
	}
    
	@Override
	public int addPaymentInfo(PaymentTradeReqDTO cPaymentTradeReqDTO) {
	  //转换并存入支付信息主表
		PayTradeMain tPayTradeMain = new PayTradeMain(); 
		//tPayTradeMain.setOrderId(cPaymentTradeReqDTO.getOrderId());
		tPayTradeMain.setSerialNo(cPaymentTradeReqDTO.getSerialNo());
		tPayTradeMain.setBizNo(cPaymentTradeReqDTO.getBizNo());
		tPayTradeMain.setBatchNo(cPaymentTradeReqDTO.getBatchNo());
		tPayTradeMain.setPayNo(cPaymentTradeReqDTO.getPayNo());
		tPayTradeMain.setMerchantCode(cPaymentTradeReqDTO.getMerchantCode());
		tPayTradeMain.setThirdpayCode(cPaymentTradeReqDTO.getThirdpayCode());
		tPayTradeMain.setBizType(cPaymentTradeReqDTO.getBizType());
		tPayTradeMain.setPayWay(cPaymentTradeReqDTO.getPayWay());
		tPayTradeMain.setPayType(cPaymentTradeReqDTO.getPayType());
		tPayTradeMain.setPayStatus(cPaymentTradeReqDTO.getPayStatus());
		tPayTradeMain.setTradeTimes(cPaymentTradeReqDTO.getTradeTimes());
		tPayTradeMain.setPayAmount(cPaymentTradeReqDTO.getPayAmount());
		tPayTradeMain.setPayAccountName(cPaymentTradeReqDTO.getPayAccountName());
		tPayTradeMain.setPayAccountMobile(cPaymentTradeReqDTO.getPayAccountMobile());
		tPayTradeMain.setPayBankName(cPaymentTradeReqDTO.getPayBankName());
		tPayTradeMain.setPayBankCode(cPaymentTradeReqDTO.getPayBankCode());
		tPayTradeMain.setPayAccountNo(cPaymentTradeReqDTO.getPayAccountNo());
		tPayTradeMain.setThirdPayNo(cPaymentTradeReqDTO.getThirdPayNo());
		tPayTradeMain.setCurrency(cPaymentTradeReqDTO.getCurrency());
		tPayTradeMain.setCreatorId(cPaymentTradeReqDTO.getCreatorId());
		tPayTradeMain.setCheckDate(DateUtil.getCurrentDate());
		tPayTradeMain.setPayDate(DateUtil.getCurrentDate());
		tPayTradeMain.setPayIdType(cPaymentTradeReqDTO.getPayIdType());
		tPayTradeMain.setPayIdNo(cPaymentTradeReqDTO.getPayIdNo());
		tPayTradeMain.setTradeDesc(cPaymentTradeReqDTO.getTradeDesc());
		tPayTradeMain.setRemark(cPaymentTradeReqDTO.getRemark());
//		tPayTradeMain.setBatchNo(cPaymentTradeReqDTO.getReqBatchNo());
		tPayTradeMain.setPayCertType(cPaymentTradeReqDTO.getPayCertType());
		tPayTradeMain.setPayOpenBank(cPaymentTradeReqDTO.getPayOpenBank());
		tPayTradeMain.setPayOpenBankArea(cPaymentTradeReqDTO.getPayOpenBankArea());
		tPayTradeMain.setCreateDate(DateUtil.getCurrentDate());  
		tPayTradeMain.setCreatorId(SystemConstants.SYS_OPERATOR);//SystemConstants.SYS_OPERATOR
		tPayTradeMain.setModifyDate(DateUtil.getCurrentDate());
		tPayTradeMain.setModifierId(SystemConstants.SYS_OPERATOR);
		tPayTradeMain.setReturnCode(cPaymentTradeReqDTO.getReturnCode());
		tPayTradeMain.setReturnMsg(cPaymentTradeReqDTO.getReturnMsg());
		tPayTradeMain.setThirdpayCode(cPaymentTradeReqDTO.getThirdpayCode());
		int addFlag = payTradeMainMapper.insert(tPayTradeMain);  //调用之前可用方法
		if (addFlag>0) {
			return tPayTradeMain.getSid();
		}else {
			return 0;
		}
	}

	@Override
	public int modifyPaymentInfo(PaymentTradeReqDTO cPaymentTradeReqDTO) {  
		PayTradeMain tPayTradeMain = new PayTradeMain();
		tPayTradeMain.setThirdPayNo(cPaymentTradeReqDTO.getThirdPayNo());
		tPayTradeMain.setReturnCode(cPaymentTradeReqDTO.getResultCode());
		tPayTradeMain.setReturnMsg(cPaymentTradeReqDTO.getResultDesc());
		tPayTradeMain.setModifyDate(DateUtil.getCurrentDate());
		PayTradeMainExample tpayTradeMainMapper = new PayTradeMainExample();
		String batchNo = cPaymentTradeReqDTO.getBatchNo();
		String payNo = cPaymentTradeReqDTO.getPayNo();
		if (StringUtil.isBlank(batchNo)&&(StringUtil.isBlank(payNo))) {
            return -1;
        }else {
            if (StringUtil.isNotBlank(batchNo)) { //根据批次号 批量更新 支付结果
                tpayTradeMainMapper.createCriteria().andBatchNoEqualTo(batchNo);
            }
            if (StringUtil.isNotBlank(payNo)) {  //单笔修改 支付状态
                tPayTradeMain.setPayStatus(cPaymentTradeReqDTO.getPayStatus());
                tpayTradeMainMapper.createCriteria().andPayNoEqualTo(payNo);
            }
            int updateFlag = payTradeMainMapper.updateByExampleSelective(tPayTradeMain, tpayTradeMainMapper);
            return updateFlag;
        }
		
	}
	
	@Override 
	public String addTransOrderBatchInfo(PaymentTradeReqDTO cPaymentTradeReqDTO) {
        PayTradeBatch tPayTradeBatch = new PayTradeBatch();
        tPayTradeBatch.setMerchantCode(cPaymentTradeReqDTO.getMerchantCode());
        tPayTradeBatch.setPayFlag(cPaymentTradeReqDTO.getPayFlag());
        tPayTradeBatch.setPayChannelId(cPaymentTradeReqDTO.getPayChannelId());
        tPayTradeBatch.setTradeNum(cPaymentTradeReqDTO.getTradeNum());
        tPayTradeBatch.setSumAmount(cPaymentTradeReqDTO.getSumAmount());
        tPayTradeBatch.setCreatorId(cPaymentTradeReqDTO.getCreatorId());
        tPayTradeBatch.setCreateDate(DateUtil.getCurrentDate());
        tPayTradeBatch.setModifierId(SystemConstants.SYS_OPERATOR);
        tPayTradeBatch.setModifyDate(DateUtil.getCurrentDate());
        tPayTradeBatch.setIsDelete("0");
       // String reqBatchNo = UUID.randomUUID().toString().substring(0,20);
        String reqBatchNo = RandomStringUtil.getRandomStringByLength(20);   //批次号这边生成 方式未定   RandomStringUtil
        tPayTradeBatch.setReqBatchNo(reqBatchNo);
        int insertFlag = payTradeBatchMapper.insertSelective(tPayTradeBatch);
        if (insertFlag>0) {
			return reqBatchNo;
		}else {
			return "false";
		}
	}

	@Override
	public int modifyTransOrderBatchInfo(PaymentTradeReqDTO cPaymentTradeReqDTO) {

		PayTradeBatch tPayTradeBatch = new PayTradeBatch();
		tPayTradeBatch.setResultCode(cPaymentTradeReqDTO.getResultCode());
		tPayTradeBatch.setResultDesc(cPaymentTradeReqDTO.getResultDesc());
		tPayTradeBatch.setDealDate(cPaymentTradeReqDTO.getDealDate());
		tPayTradeBatch.setModifyDate(DateUtil.getCurrentDate());
		tPayTradeBatch.setModifierId(SystemConstants.SYS_OPERATOR);
		PayTradeBatchExample tPayTradeBatchExample = new PayTradeBatchExample();
		tPayTradeBatchExample.createCriteria().andSidEqualTo(cPaymentTradeReqDTO.getSid()); //根据sid更新相应的信息
		int insertFlag = payTradeBatchMapper.updateByExampleSelective(tPayTradeBatch, tPayTradeBatchExample);
		return insertFlag;
	}

	@Override
	public int addBulkPaymentInfo(PaymentTradeBatchDTO cPaymentTradeBatchDTO) {
		PayTradePaymentBatch tPayTradePaymentBatch = new PayTradePaymentBatch();
		tPayTradePaymentBatch.setPayBatchNo(cPaymentTradeBatchDTO.getPayBatchNo());
		tPayTradePaymentBatch.setIfStartDate(cPaymentTradeBatchDTO.getIfStartDate());
		tPayTradePaymentBatch.setPayFlag(cPaymentTradeBatchDTO.getPayFlag());
		tPayTradePaymentBatch.setPayChannelId(cPaymentTradeBatchDTO.getPayChannelId());
		tPayTradePaymentBatch.setTradeAmount(cPaymentTradeBatchDTO.getTradeAmount());
		tPayTradePaymentBatch.setTradeNum(cPaymentTradeBatchDTO.getTradeNum());
		tPayTradePaymentBatch.setSendTime(cPaymentTradeBatchDTO.getSendTime());
		int insertFlag = payTradePaymentBatchMapper.insertSelective(tPayTradePaymentBatch);
		return insertFlag;

	}

	@Override
	public int modifyBatchPaymentInfo(PaymentTradeBatchDTO cPaymentTradeBatchDTO) {
		PayTradePaymentBatch tPayTradePaymentBatch = new PayTradePaymentBatch();
		tPayTradePaymentBatch.setIfEndDate(cPaymentTradeBatchDTO.getIfEndDate());
		tPayTradePaymentBatch.setReturnTime(cPaymentTradeBatchDTO.getReturnTime());
		tPayTradePaymentBatch.setResultCode(cPaymentTradeBatchDTO.getResultCode());
		tPayTradePaymentBatch.setResultDesc(cPaymentTradeBatchDTO.getResultDesc());
		PayTradePaymentBatchExample tPayTradePaymentBatchExample = new PayTradePaymentBatchExample();
		tPayTradePaymentBatchExample.createCriteria().andPayBatchNoEqualTo(cPaymentTradeBatchDTO.getPayBatchNo());
		int insertFlag = payTradePaymentBatchMapper.updateByExampleSelective(tPayTradePaymentBatch, tPayTradePaymentBatchExample);
		return insertFlag;
	}

	@Override
	public int addOfferRecordData(PaymentTradeBatchDTO cPaymentTradeBatchDTO) {
		PayTradeOfferLog tPayTradeOfferLog = new PayTradeOfferLog();
		tPayTradeOfferLog.setPayChannelId(cPaymentTradeBatchDTO.getPayChannelId());
		tPayTradeOfferLog.setPayBatchNo(cPaymentTradeBatchDTO.getPayBatchNo());
		tPayTradeOfferLog.setOfferDate(cPaymentTradeBatchDTO.getOfferDate());
		tPayTradeOfferLog.setOfferFile(cPaymentTradeBatchDTO.getOfferFile());
		tPayTradeOfferLog.setOfferFileStatus(cPaymentTradeBatchDTO.getOfferFileStatus());
		tPayTradeOfferLog.setCreatorId(cPaymentTradeBatchDTO.getCreatorId());
		tPayTradeOfferLog.setCreateDate(DateUtil.getCurrentDate());
		tPayTradeOfferLog.setModifierId(cPaymentTradeBatchDTO.getCreatorId());
		tPayTradeOfferLog.setModifyDate(DateUtil.getCurrentDate());
		int insertFlag = payTradeOfferLogMapper.insertSelective(tPayTradeOfferLog);
		return insertFlag;
	}

	@Override
	public int modifyOfferRecordData(PaymentTradeBatchDTO cPaymentTradeBatchDTO) {
		PayTradeOfferLog tPayTradeOfferLog = new PayTradeOfferLog();
		tPayTradeOfferLog.setReturnTime(cPaymentTradeBatchDTO.getReturnTime());
		tPayTradeOfferLog.setResultCode(cPaymentTradeBatchDTO.getResultCode());
		tPayTradeOfferLog.setResultDesc(cPaymentTradeBatchDTO.getResultDesc());
		tPayTradeOfferLog.setModifierId(cPaymentTradeBatchDTO.getModifierId());
		tPayTradeOfferLog.setModifyDate(DateUtil.getCurrentDate());
		/*if (cPaymentTradeBatchDTO.getModifierId()==null||cPaymentTradeBatchDTO.getModifyDate().equals("")) {
		    tPayTradeOfferLog.setModifyDate(DateUtil.getCurrentDate());
        }*/
		PayTradeOfferLogExample tPayTradeOfferLogExample = new PayTradeOfferLogExample();
		tPayTradeOfferLogExample.createCriteria().andPayBatchNoEqualTo(cPaymentTradeBatchDTO.getPayBatchNo());
		int updateFlag = payTradeOfferLogMapper.updateByExampleSelective(tPayTradeOfferLog, tPayTradeOfferLogExample);
		return updateFlag;
	}

	@Override
	public int addTransePayRelate(PaymentTradeReqDTO cPaymentTradeReqDTO) {
		return payTradeMapper.insertTransePayRelate(cPaymentTradeReqDTO);
	}

	@Override
	public int modifyTransePayRelate(PaymentTradeReqDTO cPaymentTradeReqDTO) {
		return payTradeMapper.updateTransePayRelate(cPaymentTradeReqDTO);
	}

	@Override
	public int addPayTradeNotifyRecord(PayTradeNotifyRecordDTO cPayTradeNotifyRecordDTO) {
		PayTradeNotifyRecord tPayTradeNotifyRecord =new PayTradeNotifyRecord();
		tPayTradeNotifyRecord.setMerchantCode(cPayTradeNotifyRecordDTO.getMerchantCode());
		tPayTradeNotifyRecord.setPayNo(cPayTradeNotifyRecordDTO.getPayNo());
		tPayTradeNotifyRecord.setNotifyUrl(cPayTradeNotifyRecordDTO.getNotifyUrl());
		tPayTradeNotifyRecord.setNotifyType(cPayTradeNotifyRecordDTO.getNotifyType());
		tPayTradeNotifyRecord.setNotifyTimes(cPayTradeNotifyRecordDTO.getNotifyTimes());
		tPayTradeNotifyRecord.setLimitNotifyTimes(cPayTradeNotifyRecordDTO.getLimitNotifyTimes());
		tPayTradeNotifyRecord.setNotifyResult(cPayTradeNotifyRecordDTO.getNotifyResult());
		tPayTradeNotifyRecord.setCreatorId(SystemConstants.SYS_OPERATOR);
		tPayTradeNotifyRecord.setCreateDate(DateUtil.getCurrentDate());
		tPayTradeNotifyRecord.setModifierId(SystemConstants.SYS_OPERATOR);
		tPayTradeNotifyRecord.setModifyDate(DateUtil.getCurrentDate());
		int addFlag = payTradeNotifyRecordMapper.insertSelective(tPayTradeNotifyRecord);
		return addFlag;
	}

	@Override
	public int modifyPayTradeNotifyRecord(PayTradeNotifyRecordDTO cPayTradeNotifyRecordDTO) {
		PayTradeNotifyRecord tPayTradeNotifyRecord =new PayTradeNotifyRecord();
		tPayTradeNotifyRecord.setNotifyUrl(cPayTradeNotifyRecordDTO.getNotifyUrl());
		tPayTradeNotifyRecord.setNotifyTimes(cPayTradeNotifyRecordDTO.getNotifyTimes());
		tPayTradeNotifyRecord.setNotifyResult(cPayTradeNotifyRecordDTO.getNotifyResult());
		tPayTradeNotifyRecord.setModifierId(cPayTradeNotifyRecordDTO.getModifierId());
		tPayTradeNotifyRecord.setModifyDate(DateUtil.getCurrentDate());  //当前时间
		PayTradeNotifyRecordExample tPayTradeNotifyRecordExample = new PayTradeNotifyRecordExample();
		tPayTradeNotifyRecordExample.createCriteria().andPayNoEqualTo(cPayTradeNotifyRecordDTO.getPayNo());
		int updateFlag = payTradeNotifyRecordMapper.updateByExampleSelective(tPayTradeNotifyRecord, tPayTradeNotifyRecordExample);
		return updateFlag;
	}

	@Override
	public int addPayTradeNotifyRecordLog(PayTradeNotifyRecordDTO cPayTradeNotifyRecordDTO) {
		PayTradeNotifyRecordLog tPayTradeNotifyRecordLog = new PayTradeNotifyRecordLog();
		tPayTradeNotifyRecordLog.setNotifyId(cPayTradeNotifyRecordDTO.getNotifyId());
		tPayTradeNotifyRecordLog.setMerchantCode(cPayTradeNotifyRecordDTO.getMerchantCode());
		tPayTradeNotifyRecordLog.setPayNo(cPayTradeNotifyRecordDTO.getPayNo());
		tPayTradeNotifyRecordLog.setRequestContent(cPayTradeNotifyRecordDTO.getRequestContent());
		tPayTradeNotifyRecordLog.setResponseContent(cPayTradeNotifyRecordDTO.getResponseContent());
		tPayTradeNotifyRecordLog.setNotifyResult(cPayTradeNotifyRecordDTO.getNotifyResult());
		tPayTradeNotifyRecordLog.setCreatorId(cPayTradeNotifyRecordDTO.getCreatorId());
		tPayTradeNotifyRecordLog.setCreateDate(cPayTradeNotifyRecordDTO.getCreateDate());
		tPayTradeNotifyRecordLog.setModifyDate(cPayTradeNotifyRecordDTO.getCreateDate());
		tPayTradeNotifyRecordLog.setModifierId(cPayTradeNotifyRecordDTO.getCreatorId());
		int addFlag = payTradeNotifyRecordLogMapper.insertSelective(tPayTradeNotifyRecordLog);
		if (addFlag>0) {
		    logger.info("----新增回调日志记录 信息成功----");
        }else {
            logger.info("----新增回调日志记录 信息失败----");
        }
		return addFlag;
	}

    @Override
    public int modifyPaymentInfoForBatch(PaymentTradeReqDTO cPaymentTradeReqDTO) {
        PayTradeMainExample tPayTradeMainExample = new PayTradeMainExample();
        tPayTradeMainExample.createCriteria().andBatchNoEqualTo(cPaymentTradeReqDTO.getBatchNo()).
        andPayAccountNoEqualTo(cPaymentTradeReqDTO.getPayAccountNo()).
        andPayAccountNameEqualTo(cPaymentTradeReqDTO.getPayAccountName()).
        andPayAmountEqualTo(cPaymentTradeReqDTO.getPayAmount());
        //更新信息 
        PayTradeMain tPayTradeMain = new PayTradeMain();
        tPayTradeMain.setReturnCode(cPaymentTradeReqDTO.getReturnCode());  //修改结果信息
        tPayTradeMain.setReturnMsg(cPaymentTradeReqDTO.getReturnMsg());    //修改结果 描述信息    
        int modifyRecord = payTradeMainMapper.updateByExampleSelective(tPayTradeMain, tPayTradeMainExample);       
        return 0;
    }	
}
